package com.naodong.shenluntiku.mvp.view.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

import com.naodong.shenluntiku.mvp.model.bean.SupportFragmentWrap;

import java.util.List;

/**
 * Created by hujie on 17/4/21.
 *
 * 少量fragment适配器
 */

public class LittleFragmentAdapter extends FragmentPagerAdapter {

    List<SupportFragmentWrap> fragments;
    FragmentManager fragmentManager;

    public LittleFragmentAdapter(FragmentManager fm, List<SupportFragmentWrap> fragments) {
        super(fm);
        this.fragmentManager = fm;
        setFragments(fragments);
    }

    public LittleFragmentAdapter(FragmentManager fm) {
        super(fm);
        this.fragmentManager = fm;
    }

    public void setFragments(List<SupportFragmentWrap> fragments) {
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments != null ? fragments.get(position).getFragment() : null;
    }

    @Override
    public int getCount() {
        return fragments != null ? fragments.size() : 0;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        SupportFragmentWrap fragment = fragments.get(position);
        return fragment.getTitle();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragmentManager.beginTransaction().show(fragment).commitNow();
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        SupportFragmentWrap fragment = fragments.get(position);
        fragmentManager.beginTransaction().hide(fragment.getFragment()).commitNow();

    }
}
